package ltd.dujiabao.performance.monitor.pm.collector;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.performance.monitor.pm.publisher.CollectPublisher;

/**
 * @author : DuJiabao
 * @Project : performance_monitor
 * @Time : 2022/2/27 20:33
 * @Desc : 收集发送数据，并且将其发布出去
 */
@Slf4j
@Aspect
@Component
public class PerformanceCollector {
    private final CollectPublisher collectPublisher;

    @Autowired
    public PerformanceCollector(CollectPublisher collectPublisher) {
        this.collectPublisher = collectPublisher;
    }

    @Pointcut("@annotation(PerformanceCollect)")
    public void annotationPointCut() {
    }

    @Around("annotationPointCut()")
    public Object time(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RequestMapping requestMapping = signature.getMethod().getAnnotation(RequestMapping.class);
        long timeConsuming = end - start;
        String[] urls = requestMapping.value();
        collectPublisher.publish(timeConsuming, urls);
        return result;
    }
}
